package com.wstuo.upgrade.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.config.category.dao.ICICategoryDAO;
import com.wstuo.common.config.category.dao.IEventCategoryDAO;
import com.wstuo.common.config.category.entity.CICategory;
import com.wstuo.common.config.category.entity.EventCategory;
import com.wstuo.common.config.category.service.IEventCategoryService;
import com.wstuo.common.config.dictionary.dao.IDataDictionaryItemsDAO;
import com.wstuo.common.config.dictionary.entity.DataDictionaryItems;
import com.wstuo.common.sla.entity.SLARule;
import com.wstuo.itsm.request.entity.Request;
import com.wstuo.itsm.knowledge.dao.IKnowledgeDAO;
import com.wstuo.itsm.knowledge.entity.KnowledgeInfo;
import com.wstuo.itsm.request.dao.IRequestDAO;
import com.wstuo.itsm.request.service.IRequestService;
import com.wstuo.itsm.request.utils.CalcPredictTimeUtils;
import com.wstuo.common.security.dao.IFunctionDAO;
import com.wstuo.common.security.dao.IHolidayDAO;
import com.wstuo.common.security.dao.IOperationDAO;
import com.wstuo.common.security.dao.IResourceDAO;
import com.wstuo.common.security.dao.IRoleDAO;
import com.wstuo.common.security.dao.IServiceTimeDAO;
import com.wstuo.common.security.dao.IUserDAO;
import com.wstuo.common.security.dto.OperationDTO;
import com.wstuo.common.security.entity.Function;
import com.wstuo.common.security.entity.Holiday;
import com.wstuo.common.security.entity.Operation;
import com.wstuo.common.security.entity.Resource;
import com.wstuo.common.security.entity.Role;
import com.wstuo.common.security.entity.ServiceTime;
import com.wstuo.common.security.entity.User;
import com.wstuo.common.security.service.IFunctionService;
import com.wstuo.common.security.service.IOperationService;
import com.wstuo.common.security.service.IRoleService;
import com.wstuo.common.security.utils.AppConfigUtils;
import com.wstuo.common.security.utils.LanguageContent;
import com.wstuo.common.util.StringUtils;

/**
 * 升级类
 * @author lenovo
 *
 */
public class UpgradeService implements IUpgradeService {
	private static final String CONFIG_DATA_FILE_PATH = AppConfigUtils.getInstance().getConfigDataPath();
	@Autowired
	private IRoleDAO roleDAO;
	@Autowired
	private IOperationDAO operationDAO;
	@Autowired
	private IFunctionDAO functionDAO;
	@Autowired
	private ICICategoryDAO cicategoryDAO;
	@Autowired
	private IResourceDAO resourceDAO;
	@Autowired
	private IFunctionService functionService;// 功能
	@Autowired
	private IOperationService operationService;// 操作
	@Autowired
	private IDataDictionaryItemsDAO dataDictionaryItemsDAO;
	@Autowired
	private IEventCategoryDAO eventCategoryDAO;
	@Autowired
    private IKnowledgeDAO knowledgeDAO;  //知识库
	@Autowired
	private IRoleService roleService;
	@Autowired
	private IUserDAO userDAO;
	private String result;
	private LanguageContent lc = LanguageContent.getInstance();
	@Autowired
	private IRequestDAO requestDAO;
	@Autowired
	private IHolidayDAO holidayDAO;
	@Autowired
	private IServiceTimeDAO serviceTimeDAO;
	@Autowired
    private IEventCategoryService eventCategoryService;

	/**
	 * 删除已有权限加载基础权限
	 */
	public String upgradePermission() {
		// 查询出角色和资源的url
		List<Resource> res = new ArrayList<Resource>();
		List<Role> list = roleDAO.findAll();
		for (Role entity : list) {
			Resource r = new Resource();
			r.setResNo(entity.getRoleId());// 角色的id
			r.setResUrl(roleService.getResourceRoleBygetResUrl(entity.getRoleId()));// 当前角色下所以的url
			res.add(r);
			entity.setResources(null);
			if (entity.getDataFlag() == null) {
				entity.setDataFlag((byte) 0);// 修改状态确保全部删除
			}
			roleDAO.merge(entity);

		}
		// 删除权限资源
		operationDAO.deleteAll();
		List<Function> li = functionDAO.findAll();
		for (Function f : li) {
			f.setParentFunction(null);
			f.setSubFunctions(null);
			functionDAO.merge(f);
		}
		functionDAO.deleteAll();
		List<Resource> lr = resourceDAO.findAll();
		for (Resource r : lr) {
			r.setRoles(null);
		}
		resourceDAO.deleteAll();
		// 加载最新的权限资源
		functionService.importFunction(getFilePath("function.csv"));// 功能
		operationService.importOperation(getFilePath("operation.csv"));// 操作
		// 给角色添加资源权限
		List<CICategory> c = cicategoryDAO.findAll();
		for (CICategory c1 : c) {
			OperationDTO operationDTO = new OperationDTO();
			operationDTO.setResName(c1.getCname());
			operationDTO.setResCode("CONFIGUREITEMCATEGORY_RES" + c1.getCno());
			operationDTO.setResUrl("CONFIGUREITEMCATEGORY_RES" + c1.getCno());
			operationDTO.setFunctionResCode("CONFIGUREITEMCATEGORY_RES");
			operationService.addOperation(operationDTO);
		}
		List<EventCategory> k = eventCategoryDAO.findAll();
		for (EventCategory k1 : k) {
			OperationDTO operationDTO = new OperationDTO();
			operationDTO.setResName(k1.getEventName() + "(" + k1.getEventId() + ")");
			operationDTO.setResCode("Knowledge_Category_" + k1.getEventId());
			operationDTO.setResUrl("Knowledge_Category_" + k1.getEventId());
			operationDTO.setFunctionResCode("Knowledge_Category_View");
			operationService.addOperation(operationDTO);
		}
		List<Role> lis = roleDAO.findAll();
		for (Role role : lis) {
			if (role.getRoleCode().equals(IRoleService.ROLE_SYSADMIN)) {// 给管理员赋值所有权限
				List<Resource> reso = resourceDAO.findAll();
				Set<Resource> sets = new HashSet<Resource>();
				for (Resource r1 : reso) {
					sets.add(r1);
				}

				role.setResources(sets);
				roleDAO.merge(role);// 更新数据
			} else {// 还原其他权限
				Set<Resource> setrs = new HashSet<Resource>();
				for (Resource ro : res) {
					if (role.getRoleId().equals(ro.getResNo())) {
						String[] resources = ro.getResUrl().toString().split(",");
						if (resources != null && resources.length > 0) {
							for (String ResUrl : resources) {
								if (StringUtils.hasText(ResUrl)) {
									Resource r = resourceDAO.findUniqueBy("resUrl", ResUrl);
									if (r != null) {
										setrs.add(r);
									}
								}
							}
						}
					}
				}
				role.setResources(setrs);
				roleDAO.merge(role);// 更新数据
			}
		}
		result = "权限升级完成！";
		return result;
	}
	/**
	 * 取得文件路径
	 */
	public String getFilePath(String fileName) {
		return CONFIG_DATA_FILE_PATH + "/cn/" + fileName;
	}
	/**
	 * 升级配置项所在位置
	 */
	@Transactional
	public String upgradeLocation() {
		List<DataDictionaryItems> li = dataDictionaryItemsDAO
				.findItemByGroupCode("location");
		if (li != null) {
			EventCategory ec = new EventCategory();
			ec = eventCategoryDAO.findUniqueBy("categoryRoot", "Location");
			if (ec != null) {
				for (DataDictionaryItems di : li) {// 所在位置树新增
					EventCategory entity = new EventCategory();
					entity.setParentEvent(ec);
					entity.setEventName(di.getDname());
					entity.setScores(Integer.valueOf(di.getDcode().toString()));
					eventCategoryDAO.save(entity);
				}
			} else {
				EventCategory ecs = new EventCategory();
				byte dataflags = 0;
				ecs.setEventId(null);
				ecs.setEventName(lc.getContent("label.dc.location"));
				ecs.setDataFlag(dataflags);
				ecs.setCategoryRoot("Location");
				eventCategoryDAO.save(ecs);
				for (DataDictionaryItems di : li) {// 所在位置树新增
					EventCategory entity = new EventCategory();
					entity.setParentEvent(ecs);
					entity.setEventName(di.getDname());
					entity.setScores(Integer.valueOf(di.getDcode().toString()));
					eventCategoryDAO.save(entity);
				}
			}
			return "success";
		} else {
			return "no update";
		}
	}
	/**
	 * 更新数据字典项
	 * 已有服务目录基础数据
	 */
	@Transactional
	public boolean subServiceList() {
		
	 	//分类表查询 root
	 	EventCategory sec = eventCategoryDAO.findUniqueBy("categoryRoot", "Service");
	 	if(sec==null){
	 		sec=new EventCategory();
	 		//添加一个父节点
	 		sec.setEventDescription("");
	 		sec.setCategoryCodeRule("");
	 		sec.setEavId(null);
	 		sec.setDataFlag(Byte.valueOf("0"));
	 		sec.setEventName("Service");
	 		sec.setCategoryRoot("Service");
	 		eventCategoryDAO.save(sec);
	 	}
		return true;
	}
	/**
	 * 更新知识库列表中
	 * 服务目录关联id
	 */
	@Transactional
	public boolean serviceDirectoryList() {
		List<KnowledgeInfo> knowledgeInfo= knowledgeDAO.findAll();
		for(KnowledgeInfo kn:knowledgeInfo){
		}
		return true;
	}
	/**
	 * 更新知识库权限
	 * @return
	 */
	@Transactional
	public boolean upgradeKnowledgeRes(){
		EventCategory eventCategory = eventCategoryDAO.findUniqueBy("categoryRoot", "Knowledge");
		List<EventCategory> listec=eventCategoryService.findSubCategoryByPath(eventCategory.getPath());
		for(EventCategory entity:listec){
			String resName = entity.getEventName()+ "("+ entity.getEventId() + ")";
			String cat = "Knowledge";
			Operation operations = operationDAO.findUniqueBy("resCode","Knowledge_Category_"+entity.getEventId());
			if(operations==null){
				OperationDTO operationDTO = new OperationDTO();
				operationDTO.setResName(resName);
				operationDTO.setResCode(cat + "_Category_" + entity.getEventId());
				operationDTO.setResUrl(cat + "_Category_" + entity.getEventId());
				operationDTO.setFunctionResCode(cat + "_Category_View");
				operationService.addOperation(operationDTO);
			}else{
				Function function = functionDAO.findUniqueBy("resCode", cat + "_Category_View");
				operations.setFunction(function);
				operationDAO.merge(operations);
			}
			
			Role role = roleDAO.findUniqueBy("roleCode", IRoleService.ROLE_SYSADMIN);
			if (role != null) {
					operations = operationDAO.findUniqueBy("resCode",cat+"_Category_"+entity.getEventId());
				if(role.getResources()!=null){
					role.getResources().add(operations);
				}else{
					Set<Resource> resources = new HashSet<Resource>();
					resources.add(operations);
					role.setResources(resources);
				}
				roleDAO.merge(role);
			}
		}
		return true;
	}
	/**
	 * 密码加密更新
	 */
	@Transactional
	public void passwordUpgrade() {
		List<User> users = userDAO.findAll();
		for (User user : users) {
			user.setPassword(user.getPassword());
			userDAO.merge(user);
		}
	}
	
	@Transactional
	public void closeRequestHanldTimeLong() {
		CalcPredictTimeUtils calcPredictTimeUtils = new CalcPredictTimeUtils();
		List<Request> list = requestDAO.findAll();
		for(Request entity : list){
			if(entity.getCloseTime()!=null && (entity.getHandleTimeLong()==null || entity.getHandleTimeLong()==0)){
				SLARule slaRule = entity.getSlaRule();
				Long ServicesNo = slaRule.getSlaContract().getServiceOrg().getOrgNo();
				List<Holiday> holidays = holidayDAO.findHolidayByServicesNo(ServicesNo);
				ServiceTime serviceTime = serviceTimeDAO.findByOrgNo(ServicesNo);
				List<Date> affdays = calcPredictTimeUtils.mergeHoliday(entity.getResponsesTime().getTime(), serviceTime, holidays);
				Long handleTimeLong = calcPredictTimeUtils.calcPendingTimeLong(entity.getResponsesTime(), entity.getCloseTime(), serviceTime, affdays);
				entity.setHandleTimeLong(handleTimeLong);
			}
		}
	}
	@Override
	public String reindexAll() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public String initIndexs() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public String delIndexs() {
		// TODO Auto-generated method stub
		return null;
	}
}
